import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { RestService } from '../../services/rest.service';
import { DataService } from './../../services/data.service';
import { ElasticsearchService } from '../../services/elasticsearch.service';
import { TraininfoDialogComponent } from './../traininfo-dialog/traininfo-dialog.component';
import { AggridNavCellComponent } from './../../shared/aggrid-nav-cell/aggrid-nav-cell.component';
import { Subscription } from 'rxjs/Rx';
import { GridOptions } from 'ag-grid/main';
import { MatDialog } from '@angular/material';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
  selector: 'app-trains',
  templateUrl: './trains.component.html',
  styleUrls: ['./trains.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class TrainsComponent implements OnDestroy {
  subscription: Subscription;

  gridOptions: GridOptions;
  columnDefs: any[];
  rowData: any[];
  offlines = [
    {train: '002', state: '离线中', FC_1_Vol: '-', FC_2_Vol: '-', update: '2017-08-02 14:09:56', fault: '-'},
    {train: '003', state: '离线中', FC_1_Vol: '-', FC_2_Vol: '-', update: '2017-08-11 09:19:20', fault: '-'},
    {train: '004', state: '离线中', FC_1_Vol: '-', FC_2_Vol: '-', update: '2017-08-15 16:10:23', fault: '-'}
  ];

  constructor(public dialog: MatDialog,
              public dataService: DataService,
              public elastic: ElasticsearchService,
              public restService: RestService) {
    this.gridOptions = this.restService.getGeneralGridOptions();
    this.gridOptions.onCellClicked = (event) => {
      if (event.colDef.field !== 'fault' || event.data['fault'] !== '故障') {
        return;
      }

      this.dialog.open(TraininfoDialogComponent, {
        width: '800px',
        disableClose: true,
        data: {
          event: event.data
        }
      }).afterClosed().subscribe(data => {
        if (!data) {
          return;
        }
      });
    };

    this.columnDefs = [
      {headerName: '列车号', field: 'train', minWidth: 70},
      {headerName: '状态', field: 'state' },
      {headerName: '燃料电池1电压', field: 'FC_1_Stack_Voltage', minWidth: 160},
      {headerName: '燃料电池2电压', field: 'FC_2_Stack_Voltage', minWidth: 160},
      {headerName: '更新时间', field: 'update', minWidth: 160},
      {headerName: '故障', field: 'fault', cellRendererFramework: AggridNavCellComponent}
    ];

    this.rowData = null;

    // check if data arrives
    if (this.elastic.lastRecord) {
      this.rowData = this.adjustData(this.elastic.lastRecord);
    }

    this.subscription = this.dataService.data$.subscribe(event => {
      if (_.isString(event)) {
        // we don't handle events
        return;
      }

      this.rowData = this.adjustData(event);
    });
  }

  onRowDoubleClicked(row) {
    console.log('row clicked');
  }

  onSelectionChanged() {
    console.log('row selection changed');
  }

  adjustData(row) {
    const trains = [];

    const singleRow = row[0];
    singleRow['train'] = '001';
    singleRow['update'] = this.restService.getUpdatedTime(singleRow);
    singleRow['state'] = '运行中';

    // get fauls and save it for later usage
    const faults = this.restService.getFaults(singleRow);
    singleRow['fault'] = _.isEmpty(faults) ? '正常' : '故障';

    trains.push(singleRow);

    this.offlines.forEach(train => {
      trains.push(train);
    });

    return trains;
  }

  onGridReady(params) {
    params.api.sizeColumnsToFit();
    if (this.elastic.lastRecord) {
      this.rowData = this.adjustData(this.elastic.lastRecord);
    }
  }

  selectAllRows() {
    this.gridOptions.api.selectAll();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
